import React, { useState, useEffect, useRef } from 'react';
import Sidebar from '../../components/sidebar';
import defaultAvatar from '../../static/defaultAvatar.png';
import axios from 'axios';
import edit from '../../static/edit.png';
import edit_w from '../../static/edit-w.png';
import deleteIcon from '../../static/delete.png';
import viewIcon from '../../static/view.png';

// 获取 token 的工具函数
const getToken = () => localStorage.getItem('token') || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTI4MjQ5NDYsInN1YiI6IjNiZDhiMzlmLWQ2MWItNDVlMi04NDEyLWZiZjM5ZmQ4MTRiYSJ9.5fvlXDEbfhRvHRtNT4VHXH1AeWckdahDdoSzK7JylrM';

const PlantIndex = () => {
    const [plants, setPlants] = useState([]);
    const [totalCount, setTotalCount] = useState(0);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    // 表单状态
    const [formData, setFormData] = useState({
        name: '',
        type: 'flower',
        status: '',
        location: '',
        description: '',
        carbon_points: 0,
        is_public: true
    });

    // 编辑状态
    const [isEditing, setIsEditing] = useState(false);
    const [editingPlantId, setEditingPlantId] = useState(null);

    // 详情模态框状态
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [currentPlantId, setCurrentPlantId] = useState(null);
    const [plantDetail, setPlantDetail] = useState(null);
    const [careRecords, setCareRecords] = useState([]);
    const [careRecordsTotal, setCareRecordsTotal] = useState(0);
    const [careRecordsLoading, setCareRecordsLoading] = useState(false);
    const [detailError, setDetailError] = useState('');

    // 养护记录表单状态
    const [careFormData, setCareFormData] = useState({
        care_type: 'watering',
        description: '',
        operated_at: new Date().toISOString().slice(0, 16), // 修正时间格式
        is_automated: false,
        is_verified: false
    });

    const [careFormLoading, setCareFormLoading] = useState(false);
    const [careFormError, setCareFormError] = useState('');

    // 滚动容器引用
    const contentContainerRef = useRef(null);

    // 加载植物数据
    const fetchPlants = async () => {
        setLoading(true);
        setError('');
        try {
            await axios.get('http://zxhp-dev.keepnuts.top/api/v1/plants?skip=0&limit=100', {
                headers: {
                    'Authorization': `Bearer ${getToken()}`
                }
            }).then(response => {
                console.log('植物列表响应:', response.data);
                setPlants(response.data.data || []);
                setTotalCount(response.data.count || 0);
            });
        } catch (err) {
            setError('获取植物列表失败，请检查网络或重试');
            console.error('请求错误:', err);
        } finally {
            setLoading(false);
        }
    };

    // 获取植物详情
    const fetchPlantDetail = async (plantId) => {
        setShowDetailModal(true);
        setCurrentPlantId(plantId);
        setCareRecordsLoading(true);
        setDetailError('');
        setCareFormError('');

        try {
            // 先获取植物详情
            const plantResponse = await axios.get(`http://zxhp-dev.keepnuts.top/api/v1/plants/${plantId}`, {
                headers: {
                    'Authorization': `Bearer ${getToken()}`
                }
            });
            // 再获取养护记录
            const recordsResponse = await axios.get(`http://zxhp-dev.keepnuts.top/api/v1/plants/${plantId}/care-records?skip=0&limit=100`, {
                headers: {
                    'Authorization': `Bearer ${getToken()}`
                }
            });
            console.log('植物详情响应:', plantResponse.data);
            console.log('养护记录响应:', recordsResponse.data);
            setPlantDetail(plantResponse.data);
            setCareRecords(recordsResponse.data.data || []);
            setCareRecordsTotal(recordsResponse.data.count || 0);

            // 重置养护记录表单
            setCareFormData({
                care_type: 'watering',
                description: '',
                operated_at: new Date().toISOString().slice(0, 16), // 修正时间格式
                is_automated: false,
                is_verified: false
            });
        } catch (error) {
            setDetailError('获取植物详情失败，请稍后重试');
            console.error('获取详情失败:', error);
        } finally {
            setCareRecordsLoading(false);
        }
    };

    // 创建养护记录
    const createCareRecord = async () => {
        if (!currentPlantId) return;

        setCareFormLoading(true);
        setCareFormError('');

        // 表单验证
        if (!careFormData.care_type) {
            setCareFormError('请选择养护类型');
            setCareFormLoading(false);
            return;
        }
        if (!careFormData.operated_at) {
            setCareFormError('请选择操作时间');
            setCareFormLoading(false);
            return;
        }

        try {
            // 构造请求体
            const requestBody = {
                care_type: careFormData.care_type,
                description: careFormData.description,
                operated_at: careFormData.operated_at,
                is_automated: careFormData.is_automated,
                is_verified: careFormData.is_verified
            };

            await axios.post(
                `http://zxhp-dev.keepnuts.top/api/v1/plants/${currentPlantId}/care-records`,
                requestBody,
                {
                    headers: {
                        'Authorization': `Bearer ${getToken()}`,
                        'Content-Type': 'application/json'
                    }
                }
            );

            // 重新获取养护记录
            fetchPlantDetail(currentPlantId);
            setCareFormError('');
        } catch (error) {
            setCareFormError('创建养护记录失败，请稍后重试');
            console.error('创建养护记录失败:', error);
        } finally {
            setCareFormLoading(false);
        }
    };

    // 处理养护记录表单变化
    const handleCareFormChange = (e) => {
        const { name, value, type, checked } = e.target;
        setCareFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

    // 关闭详情模态框
    const handleCloseDetailModal = () => {
        setShowDetailModal(false);
        setPlantDetail(null);
        setCareRecords([]);
        setCareRecordsTotal(0);
    };

    // 组件挂载时加载数据
    useEffect(() => {
        fetchPlants();
    }, []);

    // 处理表单输入变化
    const handleFormChange = (e) => {
        const { name, value, type, checked } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

    // 重置表单
    const resetForm = () => {
        setFormData({
            name: '',
            type: 'flower',
            status: '', // 重置为''（空字符串）
            location: '',
            description: '',
            carbon_points: 0,
            is_public: true
        });
    };

    // 添加植物
    const handleAddPlant = async () => {
        // 表单验证
        if (!formData.name.trim()) {
            setError('植物名称不能为空');
            return;
        }
        if (formData.name.length > 100) {
            setError('植物名称不能超过100个字符');
            return;
        }
        if (formData.location.length > 255) {
            setError('位置信息不能超过255个字符');
            return;
        }
        if (isNaN(formData.carbon_points) || parseInt(formData.carbon_points) < 0) {
            setError('碳积分必须为非负整数');
            return;
        }

        try {
            // 构造请求体
            const requestBody = {
                name: formData.name.trim(),
                type: formData.type,
                ...(formData.status ? { status: formData.status } : {}),
                location: formData.location.trim() || '',
                description: formData.description || '',
                carbon_points: parseInt(formData.carbon_points) || 0,
                is_public: formData.is_public !== undefined ? formData.is_public : true
            };

            await axios.post(
                'http://zxhp-dev.keepnuts.top/api/v1/plants',
                requestBody,
                {
                    headers: {
                        'Authorization': `Bearer ${getToken()}`,
                        'Content-Type': 'application/json'
                    }
                }
            );

            setError('');
            fetchPlants();
            resetForm();

        } catch (error) {
            let errorMsg = '添加植物失败，请稍后重试';
            if (error.response) {
                if (error.response.status === 400) {
                    errorMsg = error.response.data.message || '参数错误，请检查输入';
                } else if (error.response.status === 401) {
                    errorMsg = '未登录或登录已过期，请重新登录';
                } else if (error.response.status === 403) {
                    errorMsg = '没有权限创建植物';
                }
            }
            setError(errorMsg);
            console.error('添加植物失败:', error);
        }
    };

    // 开始编辑植物
    const handleEditPlant = (plant) => {
        console.log('编辑按钮被点击');
        setIsEditing(true);
        setEditingPlantId(plant.id);
        setFormData({
            name: plant.name,
            type: plant.type,
            status: plant.status,
            location: plant.location,
            description: plant.description,
            carbon_points: plant.carbon_points,
            is_public: plant.is_public
        });

        // 延迟执行滚动，确保DOM更新完成
        setTimeout(() => {
            if (contentContainerRef.current) {
                contentContainerRef.current.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            }
        }, 100);
    };

    // 更新植物
    const handleUpdatePlant = async () => {
        if (!editingPlantId) return;

        // 表单验证
        if (!formData.name.trim()) {
            setError('植物名称不能为空');
            return;
        }
        if (formData.name.length > 100) {
            setError('植物名称不能超过100个字符');
            return;
        }
        if (formData.location.length > 255) {
            setError('位置信息不能超过255个字符');
            return;
        }
        if (isNaN(formData.carbon_points) || parseInt(formData.carbon_points) < 0) {
            setError('碳积分必须为非负整数');
            return;
        }

        try {
            // 构造请求体
            const requestBody = {
                name: formData.name.trim(),
                type: formData.type,
                status: formData.status,
                location: formData.location.trim(),
                description: formData.description,
                carbon_points: parseInt(formData.carbon_points) || 0,
                is_public: formData.is_public
            };

            await axios.put(`http://zxhp-dev.keepnuts.top/api/v1/plants/${editingPlantId}`,
                requestBody,
                {
                    headers: {
                        'Authorization': `Bearer ${getToken()}`
                    }
                }
            );
            fetchPlants();
            resetForm();
            setIsEditing(false);
            setEditingPlantId(null);
            setError('');
        } catch (error) {
            setError('更新植物失败，请稍后重试');
            console.error('更新植物失败:', error);
        }
    };

    // 取消编辑
    const handleCancelEdit = () => {
        setIsEditing(false);
        setEditingPlantId(null);
        resetForm();
    };

    // 删除植物
    const handleDeletePlant = async (id) => {
        // 优化弹窗
        if (!window.confirm('确定要删除此植物吗？此操作不可恢复。')) return;
        try {
            await axios.delete(`http://zxhp-dev.keepnuts.top/api/v1/plants/${id}`, {
                headers: {
                    'Authorization': `Bearer ${getToken()}`
                }
            });
            fetchPlants();
        } catch (error) {
            setError('删除植物失败，请稍后重试');
            console.error('删除植物失败:', error);
        }
    };

    // 【修正1：完善状态映射表，包含所有可能的状态】
    const statusMap = {
        'unknown': '未知',
        'healthy': '健康',
        'warning': '警告',
        'critical': '严重',
        'growing': '生长中',
        'mature': '成熟',
        'dead': '枯萎'
    };

    // 【修正2：状态样式映射（统一管理不同状态的样式）】
    const statusStyleMap = {
        'healthy': 'bg-green-100 text-green-800',
        'warning': 'bg-yellow-100 text-yellow-800',
        'critical': 'bg-red-100 text-red-800',
        'growing': 'bg-blue-100 text-blue-800',
        'mature': 'bg-purple-100 text-purple-800',
        'dead': 'bg-gray-100 text-gray-800',
        'unknown': 'bg-gray-100 text-gray-800'
    };

    // 【新增：养护类型样式映射】
    const careTypeStyleMap = {
        'watering': 'bg-blue-100 text-blue-800',
        'fertilizing': 'bg-yellow-100 text-yellow-800',
        'pruning': 'bg-green-100 text-green-800',
        'pest_control': 'bg-red-100 text-red-800',
        'other': 'bg-gray-100 text-gray-800'
    };

    return (
        <div className="flex h-screen">
            <Sidebar />
            <div className="flex-1 flex flex-col">
                <header className="flex justify-between items-center p-4 bg-white shadow">
                    <h1 className="text-xl font-semibold">植物管理</h1>
                    <div className="flex items-center">
                        <span className="mr-2">用户名</span>
                        <img className='w-10 h-10 rounded-full border-black border-2' src={defaultAvatar} />
                    </div>
                </header>
                {/* 给内容容器添加ref */}
                <div ref={contentContainerRef} className="flex-1 p-6 overflow-y-auto w-full">
                    <div className="mb-6">
                        <div>
                            <span className="text-gray-500">共 {totalCount} 条植物记录</span>
                        </div>
                        {/* 新建/编辑植物表单 */}
                        <div className="w-full">
                            <div className="bg-white p-4 rounded mb-4">
                                <h3 className="text-sm font-medium text-gray-700 mb-3">
                                    {isEditing ? <span className="text-blue-600 font-bold">编辑植物</span> : '新建植物'}
                                </h3>
                                <div className="flex-2">
                                    <div>
                                        <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">植物名称 <span className="text-red-500">*</span></label>
                                        <input
                                            type="text"
                                            id="name"
                                            name="name"
                                            value={formData.name}
                                            onChange={handleFormChange}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="请输入植物名称"
                                        />
                                        {!formData.name.trim() && <p className="text-red-500 text-xs mt-1">请输入植物名称</p>}
                                        {formData.name.length > 100 && <p className="text-red-500 text-xs mt-1">植物名称不能超过100个字符</p>}
                                    </div>

                                    <div className="grid grid-cols-2 gap-3 mt-2">
                                        <div>
                                            <label htmlFor="type" className="block text-sm font-medium text-gray-700 mb-1">植物类型</label>
                                            <select
                                                id="type"
                                                name="type"
                                                value={formData.type}
                                                onChange={handleFormChange}
                                                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            >
                                                <option value="flower">花卉</option>
                                                <option value="tree">树木</option>
                                                <option value="shrub">灌木</option>
                                                <option value="grass">草本</option>
                                                <option value="other">其他</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label htmlFor="status" className="block text-sm font-medium text-gray-700 mb-1">植物状态</label>
                                            <select
                                                id="status"
                                                name="status"
                                                value={formData.status}
                                                onChange={handleFormChange}
                                                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            >
                                                <option value="">请选择状态</option> {/* 新增空选项 */}
                                                <option value="unknown">未知</option>
                                                <option value="healthy">健康</option>
                                                <option value="warning">警告</option>
                                                <option value="critical">严重</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div className='mt-2'>
                                        <label htmlFor="location" className="block text-sm font-medium text-gray-700 mb-1">所在位置</label>
                                        <input
                                            type="text"
                                            id="location"
                                            name="location"
                                            value={formData.location}
                                            onChange={handleFormChange}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="请输入植物位置"
                                        />
                                        {formData.location.length > 255 && <p className="text-red-500 text-xs mt-1">位置信息不能超过255个字符</p>}
                                    </div>

                                    <div className='mt-2'>
                                        <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">植物描述</label>
                                        <textarea
                                            id="description"
                                            name="description"
                                            value={formData.description}
                                            onChange={handleFormChange}
                                            rows="2"
                                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="请输入植物描述"
                                        />
                                    </div>

                                    <div className="grid grid-cols-2 gap-3">
                                        <div>
                                            <label htmlFor="carbon_points" className="block text-sm font-medium text-gray-700 mb-1">碳积分</label>
                                            <input
                                                type="number"
                                                id="carbon_points"
                                                name="carbon_points"
                                                value={formData.carbon_points}
                                                onChange={handleFormChange}
                                                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                                placeholder="0"
                                            />
                                        </div>
                                        <div className="flex items-end">
                                            <label htmlFor="is_public" className="flex items-center">
                                                <input
                                                    type="checkbox"
                                                    id="is_public"
                                                    name="is_public"
                                                    checked={formData.is_public}
                                                    onChange={handleFormChange}
                                                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                                />
                                                <span className="ml-2 block text-sm text-gray-700">设为公开</span>
                                            </label>
                                        </div>
                                    </div>

                                    <div className="flex mt-2">
                                        {isEditing ? (
                                            <>
                                                <button
                                                    onClick={handleUpdatePlant}
                                                    className="flex-1 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors flex items-center justify-center"
                                                >
                                                    <img src={edit_w} className='w-4 h-4 mr-2' />
                                                    保存修改
                                                </button>
                                                <button
                                                    onClick={handleCancelEdit}
                                                    className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors"
                                                >
                                                    取消
                                                </button>
                                            </>
                                        ) : (
                                            <button
                                                onClick={handleAddPlant}
                                                className="w-full px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors flex items-center justify-center"
                                            >
                                                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
                                                新建植物
                                            </button>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* 加载和错误提示 */}
                    {loading && (
                        <div className="flex items-center justify-center py-12">
                            <div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-blue-500"></div>
                            <span className="ml-3 text-gray-500">加载中...</span>
                        </div>
                    )}

                    {error && (
                        <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
                            <div className="flex">
                                <div className="flex-shrink-0">
                                    <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                                        <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                                    </svg>
                                </div>
                                <div className="ml-3">
                                    <p className="text-sm text-red-700">{error}</p>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 表格 */}
                    <div className="overflow-x-auto">
                        <table className="w-full min-w-[800px] divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                                <tr>
                                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">序号</th>
                                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">位置</th>
                                    <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">碳积分</th>
                                    <th className="py-3 px-4 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {plants.length > 0 ? (
                                    plants.map((plant, index) => (
                                        <tr key={plant.id} className="hover:bg-gray-50 transition-colors">
                                            <td className="px-4 py-3 text-sm text-gray-900 break-words">{index + 1}</td>
                                            <td className="px-4 py-3 text-sm font-medium text-gray-900 break-words">{plant.name}</td>
                                            <td className="px-4 py-3 text-sm text-gray-900 break-words">
                                                <span className={`px-2 py-1 text-xs font-medium rounded-full ${plant.type === 'flower' ? 'bg-pink-100 text-pink-800' :
                                                    plant.type === 'tree' ? 'bg-green-100 text-green-800' :
                                                        plant.type === 'shrub' ? 'bg-lime-100 text-lime-800' :
                                                            plant.type === 'grass' ? 'bg-teal-100 text-teal-800' :
                                                                'bg-gray-100 text-gray-800'
                                                    }`}>
                                                    {plant.type === 'flower' ? '花卉' :
                                                        plant.type === 'tree' ? '树木' :
                                                            plant.type === 'shrub' ? '灌木' :
                                                                plant.type === 'grass' ? '草本' :
                                                                    '其他'}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3 text-sm text-gray-900 break-words">
                                                {/* 【修正3：使用statusMap和statusStyleMap统一处理状态显示】 */}
                                                <span className={`px-2 py-1 text-xs font-medium rounded-full ${statusStyleMap[plant.status] || 'bg-gray-100 text-gray-800'}`}>
                                                    {statusMap[plant.status] || plant.status}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3 text-sm text-gray-900 break-words">{plant.location}</td>
                                            <td className="px-4 py-3 text-sm text-gray-900 break-words">{plant.carbon_points}</td>
                                            <td className="px-4 py-3 text-center text-sm">
                                                <div className="flex justify-center space-x-2">
                                                    <button
                                                        onClick={() => fetchPlantDetail(plant.id)}
                                                        className="inline-flex items-center px-3 py-1 text-sm font-medium text-green-700 bg-green-100 rounded-md hover:bg-green-200 transition-colors"
                                                    >
                                                        <img src={viewIcon} className='w-4 h-4 mr-1' />
                                                        详情
                                                    </button>
                                                    <button
                                                        onClick={() => handleEditPlant(plant)}
                                                        className="inline-flex items-center px-3 py-1 text-sm font-medium text-blue-700 bg-blue-100 rounded-md hover:bg-blue-200 transition-colors"
                                                    >
                                                        <img src={edit} className='w-3 h-3 mr-1' />
                                                        编辑
                                                    </button>
                                                    <button
                                                        onClick={() => handleDeletePlant(plant.id)}
                                                        className="inline-flex items-center px-3 py-1 text-sm font-medium text-red-700 bg-red-100 rounded-md hover:bg-red-200 transition-colors"
                                                    >
                                                        <img src={deleteIcon} className='w-3 h-3 mr-1' />
                                                        删除
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                ) : !loading ? (
                                    <tr>
                                        <td colSpan="7" className="px-4 py-12 text-center text-gray-500">
                                            <div className="flex flex-col items-center">
                                                <svg className="w-12 h-12 text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
                                                <p>暂无植物数据</p>
                                                <p className="text-xs mt-1 text-gray-400">请在左侧表单添加新植物</p>
                                            </div>
                                        </td>
                                    </tr>
                                ) : null}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {/* 详情模态框 */}
            {showDetailModal && (
                <div className="fixed inset-0 bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
                        <div className="p-6">
                            <div className="flex justify-between items-start mb-4">
                                <h3 className="text-xl font-semibold text-gray-900">植物详情</h3>
                                <button onClick={handleCloseDetailModal} className="text-gray-400 hover:text-gray-500">
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>

                            {careRecordsLoading ? (
                                <div className="flex items-center justify-center py-8">
                                    <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
                                    <span className="ml-2 text-gray-500">加载详情中...</span>
                                </div>
                            ) : detailError ? (
                                <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-4">
                                    <p className="text-sm text-red-700">{detailError}</p>
                                </div>
                            ) : plantDetail ? (
                                <>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                                        <div>
                                            <h4 className="text-lg font-medium text-gray-900 mb-2">{plantDetail.name}</h4>
                                            <div className="grid grid-cols-2 gap-4">
                                                <div>
                                                    <p className="text-sm text-gray-500">类型</p>
                                                    <p className="text-base font-medium text-gray-900">
                                                        {plantDetail.type === 'flower' ? '花卉' :
                                                            plantDetail.type === 'tree' ? '树木' :
                                                                plantDetail.type === 'shrub' ? '灌木' :
                                                                    plantDetail.type === 'grass' ? '草本' :
                                                                        '其他'}
                                                    </p>
                                                </div>
                                                <div>
                                                    <p className="text-sm text-gray-500">状态</p>
                                                    <p className="text-base font-medium text-gray-900">
                                                        {statusMap[plantDetail.status] || plantDetail.status}
                                                    </p>
                                                </div>
                                                <div>
                                                    <p className="text-sm text-gray-500">位置</p>
                                                    <p className="text-base font-medium text-gray-900">{plantDetail.location}</p>
                                                </div>
                                                <div>
                                                    <p className="text-sm text-gray-500">碳积分</p>
                                                    <p className="text-base font-medium text-gray-900">{plantDetail.carbon_points}</p>
                                                </div>
                                                <div>
                                                    <p className="text-sm text-gray-500">创建时间</p>
                                                    <p className="text-base font-medium text-gray-900">{new Date(plantDetail.created_at).toLocaleString()}</p>
                                                </div>
                                                <div>
                                                    <p className="text-sm text-gray-500">更新时间</p>
                                                    <p className="text-base font-medium text-gray-900">{new Date(plantDetail.updated_at).toLocaleString()}</p>
                                                </div>
                                            </div>
                                            <div className="mt-4">
                                                <p className="text-sm text-gray-500">描述</p>
                                                <p className="text-base text-gray-900">{plantDetail.description || '无描述信息'}</p>
                                            </div>
                                        </div>
                                        <div className="bg-gray-100 rounded-lg p-4">
                                            <h4 className="text-sm font-medium text-gray-700 mb-2">添加养护记录</h4>
                                            {careFormError && (
                                                <div className="bg-red-50 border-l-4 border-red-400 p-2 mb-2">
                                                    <p className="text-xs text-red-700">{careFormError}</p>
                                                </div>
                                            )}
                                            <div className="space-y-3">
                                                <div>
                                                    <label htmlFor="care_type" className="block text-xs font-medium text-gray-700 mb-1">养护类型</label>
                                                    <select
                                                        id="care_type"
                                                        name="care_type"
                                                        value={careFormData.care_type}
                                                        onChange={handleCareFormChange}
                                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                                                    >
                                                        <option value="watering">浇水</option>
                                                        <option value="fertilizing">施肥</option>
                                                        <option value="pruning">修剪</option>
                                                        <option value="pest_control">病虫害防治</option>
                                                        <option value="other">其他</option>
                                                    </select>
                                                </div>
                                                <div>
                                                    <label htmlFor="description" className="block text-xs font-medium text-gray-700 mb-1">描述</label>
                                                    <textarea
                                                        id="description"
                                                        name="description"
                                                        value={careFormData.description}
                                                        onChange={handleCareFormChange}
                                                        rows="2"
                                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                                                        placeholder="请输入养护描述"
                                                    />
                                                </div>
                                                <div>
                                                    <label htmlFor="operated_at" className="block text-xs font-medium text-gray-700 mb-1">操作时间</label>
                                                    <input
                                                        type="datetime-local"
                                                        id="operated_at"
                                                        name="operated_at"
                                                        value={careFormData.operated_at}
                                                        onChange={handleCareFormChange}
                                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                                                    />
                                                </div>
                                                <div className="flex items-center">
                                                    <input
                                                        type="checkbox"
                                                        id="is_automated"
                                                        name="is_automated"
                                                        checked={careFormData.is_automated}
                                                        onChange={handleCareFormChange}
                                                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                                    />
                                                    <label htmlFor="is_automated" className="ml-2 block text-xs text-gray-700">自动操作</label>
                                                </div>
                                                <div className="flex items-center">
                                                    <input
                                                        type="checkbox"
                                                        id="is_verified"
                                                        name="is_verified"
                                                        checked={careFormData.is_verified}
                                                        onChange={handleCareFormChange}
                                                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                                    />
                                                    <label htmlFor="is_verified" className="ml-2 block text-xs text-gray-700">已验证</label>
                                                </div>
                                                <button
                                                    onClick={createCareRecord}
                                                    disabled={careFormLoading}
                                                    className="w-full bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 transition-colors text-sm"
                                                >
                                                    {careFormLoading ? '添加中...' : '添加养护记录'}
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <div>
                                        <h4 className="text-sm font-medium text-gray-700 mb-3">养护记录 ({careRecordsTotal})</h4>
                                        <div className="overflow-x-auto">
                                            <table className="min-w-full divide-y divide-gray-200">
                                                <thead className="bg-gray-50">
                                                    <tr>
                                                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                                                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作时间</th>
                                                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作方式</th>
                                                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                                    </tr>
                                                </thead>
                                                <tbody className="bg-white divide-y divide-gray-200">
                                                    {careRecords.length > 0 ? (
                                                        careRecords.map(record => (
                                                            <tr key={record.id} className="hover:bg-gray-50">
                                                                <td className="px-3 py-2 whitespace-nowrap">
                                                                    {/* 【修正4：使用careTypeStyleMap统一处理养护类型样式】 */}
                                                                    <span className={`px-2 py-1 text-xs font-medium rounded-full ${careTypeStyleMap[record.care_type] || 'bg-gray-100 text-gray-800'}`}>
                                                                        {record.care_type === 'watering' ? '浇水' :
                                                                            record.care_type === 'fertilizing' ? '施肥' :
                                                                                record.care_type === 'pruning' ? '修剪' :
                                                                                    record.care_type === 'pest_control' ? '病虫害防治' :
                                                                                        '其他'}
                                                                    </span>
                                                                </td>
                                                                <td className="px-3 py-2 text-sm text-gray-900 max-w-xs truncate">{record.description}</td>
                                                                <td className="px-3 py-2 text-sm text-gray-900">{new Date(record.operated_at).toLocaleString()}</td>
                                                                <td className="px-3 py-2 text-sm text-gray-900">
                                                                    {record.is_automated ? '自动' : '手动'}
                                                                </td>
                                                                <td className="px-3 py-2 text-sm text-gray-900">
                                                                    {record.is_verified ? '已验证' : '待验证'}
                                                                </td>
                                                            </tr>
                                                        ))
                                                    ) : (
                                                        <tr>
                                                            <td colSpan="5" className="px-3 py-4 text-center text-sm text-gray-500">暂无养护记录</td>
                                                        </tr>
                                                    )}
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </>
                            ) : null}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default PlantIndex;